<template>
  <grid-layout :layout="layout" :loading="loading">
    <template #left>
      <instruction-list v-model="currentId" :data-list="dataList" style="width: 100%" @change="onSelect" />
    </template>
    <template #right>
      <div class="instruction-details-right">
        <div style="display: flex; justify-content: space-between; align-items: center; margin: 0 0 16px">
          <div style="font-size: 16px; font-weight: bold; color: #1890ff">
            接收单位共计{{ receivingNum }}个，已签收{{ receivedNum }}个
          </div>
          <a-space v-if="isCloseCase !== true">
            <a-button v-if="canIHandle && canIReceive" default type="primary" @click="receive">签收</a-button>
            <a-button v-if="canIHandle && canIFeedback && isForMe && !isEnded" default type="primary" @click="feedback"
              >反馈</a-button
            >
            <a-button v-auth="'zlgl:gj'" v-if="canIHandle && !isEnded" danger type="primary" @click="followUp"
              >跟进</a-button
            >
            <a-button
              v-if="canIExportDetails"
              danger
              type="primary"
              :href="exportFile"
              target="_blank"
              download="处置详情"
              >导出处置详情</a-button
            >
          </a-space>
        </div>
        <a-form
          v-if="isCloseCase === true && isMine && !isEnded"
          ref="formRef"
          :model="formData"
          style="margin: 0 0 16px"
        >
          <a-form-item name="jams" :rules="{ required: true, message: '请填写结案说明' }" :label-col="{ span: 24 }">
            <template #label>
              <div style="font-weight: bold; color: #000">结案说明：</div>
            </template>
            <a-textarea v-model:value="formData.jams" placeholder="请填写结案说明"></a-textarea>
          </a-form-item>
          <a-form-item>
            <div style="display: flex; justify-content: center">
              <a-button type="primary" @click="closeCase">结案</a-button>
            </div>
          </a-form-item>
        </a-form>
        <descriptions-group :columns="descriptionsList" :data-source="dataSource" :col-span="12" />
        <div class="details-item">
          <div class="details-item-label">指令内容：</div>
          <div
            v-html="dataSource.zlnr"
            style="
              min-height: 100px;
              padding: 10px;
              border: 1px solid #dce2e6;
              border-radius: 4px;
              white-space: pre-wrap;
            "
          ></div>
        </div>
        <div v-if="dataSource.gjnr" class="details-item">
          <div class="details-item-label">跟进内容：</div>
          <div
            v-html="dataSource.gjnr"
            style="
              min-height: 100px;
              padding: 10px;
              border: 1px solid #dce2e6;
              border-radius: 4px;
              white-space: pre-wrap;
            "
          ></div>
        </div>
        <div class="details-item">
          <div class="details-item-label">附件：</div>
          <attachment-list :data="dataSource.fjdz" :name-list="dataSource.fjmc" :col-span="3" display-type="list">
            <template #empty>无</template>
          </attachment-list>
        </div>
        <div style="width: 100%; margin: 16px 0 0">
          <div class="title">各部门签收/回复详情</div>
          <template v-if="records && records.length">
            <div v-for="item of records" style="margin-bottom: 10px">
              <instruction-details-item :data="item" />
            </div>
          </template>
          <template v-else> 暂无签收/回复 </template>
        </div>
      </div>
    </template>
  </grid-layout>
</template>

<script>
import AttachmentList from '@gis/lib/components/attachment-list.vue';
import TimeLine from '@gis/lib/components/antd-time-line/index.vue';
import DescriptionsGroup from '@gis/lib/components/descriptions/index.vue';
import GridLayout from '@gis/lib/layouts/grid-layout.vue';
import InstructionDetailsItem from './instruction-details-item.vue';
import InstructionList from './instruction-list.vue';
import { handleCommonResult, handleFormResult } from '@gis/lib/utils/resolver.js';
import { exportInstructionDetails, setInstructionStatus } from '@gis/lib/api';
import { instructionDetails, instructionGenJinList, instructionHfqs } from '@gis/lib/api';
import { getDwLength, getIsEnded, getIsForMe, getIsMine, getIsReceived } from '../utils.js';
import { openInstructionFeedbackDialog, openInstructionFollowUpDialog } from '../dialog.js';
import get from 'lodash-es/get.js';

export default {
  name: 'instruction-details',
  inject: {
    dialog: { default: () => ({ style: {} }) },
  },
  components: {
    InstructionList,
    InstructionDetailsItem,
    AttachmentList,
    GridLayout,
    TimeLine,
    DescriptionsGroup,
  },
  props: {
    id: { type: String, default: undefined },
    isCloseCase: { type: Boolean, default: false },
    canIHandle: { type: Boolean, default: false },
    canIExportDetails: { type: Boolean, default: true },
  },
  data() {
    return {
      descriptionsList: [
        { label: '指令编号', key: 'zlbh' },
        { label: '指令名称', key: 'zlmc' },
        { label: '来源单位', key: 'fbdw' },
        { label: '来源人员', key: 'cjr' },
        { label: '指令级别', key: 'zljb' },
        { label: '回复期限', key: 'hfzq' },
        { label: '发布时间', key: 'fbrq' },
        // { label: '指令内容', key: 'zlnr' },
      ],
      layout: [
        { name: 'left', colSpan: 5 },
        // { name: 'left', colSpan: 0 },
        { name: 'right', colSpan: 19 },
        // { name: 'right', colSpan: 24 },
      ],
      details: {},
      dataSource: {},
      dataList: [],
      records: [],
      formData: {},
      loading: false,
      currentId: undefined,
    };
  },
  computed: {
    isMine() {
      return getIsMine(get(this.dataSource, 'cjrid'));
    },
    isForMe() {
      return getIsForMe(get(this.dataSource, 'qsdwbm'));
    },
    isEnded() {
      return getIsEnded(this.dataSource);
    },
    isReceived() {
      return getIsReceived(get(this.dataSource, 'sqdwbm'));
    },
    receivedNum() {
      return getDwLength(get(this.dataSource, 'sqdwbm'));
    },
    receivingNum() {
      return getDwLength(get(this.dataSource, 'qsdwbm'));
    },
    canIReceive() {
      return get(this.details, 'sfxyqshf') == 1;
    },
    canIFeedback() {
      return get(this.details, 'sfxyfk') == 1;
    },
  },
  created() {
    if (!this.id) {
      throw new Error('id is not valid');
    }
    this.currentId = this.id;
    this.getDetails();
  },
  methods: {
    exportFile() {
      return exportInstructionDetails({ id: this.currentId });
    },
    onSelect(scope) {
      this.currentId = get(scope, 'key');
      this.getDetails();
    },
    async receive(refresh) {
      handleFormResult(await instructionHfqs({ id: this.currentId }), {
        onOk: () => refresh !== false && this.getDetails(),
      });
    },
    async followUp() {
      await openInstructionFollowUpDialog({ id: this.id });
      await this.getDetails();
    },
    async feedback() {
      await openInstructionFeedbackDialog({
        id: this.currentId,
        onBeforeFeedback: async () => {
          if (this.isForMe && this.isReceived !== true) {
            await this.receive(false);
          }
        },
      });
      await this.getDetails();
    },
    async getGJZlList(data) {
      const list = handleCommonResult(await instructionGenJinList({ id: this.id }));
      return list.map((item) => {
        return {
          key: get(item, 'zid') || Date.now(),
          name: get(item, 'title'),
          time: get(item, 'gjsj'),
          content: get(item, 'qsdwmc'),
          isEnded: get(data, 'isEnded'),
          isForMe: getIsForMe(get(item, 'qsdwbm')),
          isReceived: getIsReceived(get(item, 'sqdwbm')),
        };
      });
    },
    async getDetails(options = {}) {
      let { id } = options;
      if (id === undefined) {
        id = this.currentId;
      }
      this.loading = true;
      this.details = handleCommonResult(await instructionDetails({ id }).catch(() => {}), {
        defaultValue: {},
      });
      const { instructions = {}, dwqshf = [], gjxx } = this.details;
      const gjnr = get(gjxx, 'gjnr');
      this.dataSource = Object.assign({}, instructions, { gjnr });
      this.records = dwqshf.sort((p, n) => (p.sfqshf == '1' ? 1 : -1));
      // console.log(this.records);
      if (id === this.id) {
        this.mainZL = [
          {
            key: this.id,
            name: '指令信息',
            time: get(instructions, 'fbrq'),
            content: get(instructions, 'qsdwmc'),
            isEnded: getIsEnded(instructions),
            isForMe: getIsForMe(get(instructions, 'qsdwbm')),
            isReceived: getIsReceived(get(instructions, 'sqdwbm')),
          },
        ];
      }
      const childZl = await this.getGJZlList(this.mainZL[0]);
      this.dataList = [].concat(this.mainZL, childZl);
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    async closeCase() {
      await this.$refs.formRef.validate();
      const params = { id: this.id, zlzt: '已结案', jams: this.formData.jams };
      handleFormResult(await setInstructionStatus(params), {
        onOk: () => this.$emit('closeDialog'),
      });
    },
  },
};
</script>

<style scoped lang="less">
.details-item {
  margin: 16px 0;
  .details-item-label {
    margin: 0 0 10px;
    font-weight: bold;
    color: #000;
  }
}
.title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 10px;
}
</style>
